package com.hermit.qmst.UI.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.R;
import com.hermit.qmst.UI.dilog.CustomDialog;
import com.hermit.qmst.request.RequestTaskInterface;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.Log;
import com.hermit.qmst.tools.ParseXML;
import com.hermit.qmst.tools.Preferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by hermithermit on 15/2/16.
 */
public class RegisterActivity extends Activity implements View.OnClickListener, RequestTaskInterface {
    private String TAG = "注册：RegisterActivity";
    private String mPhone;
    //private String mPassword;
    private String mVerify = "";

    private EditText metPhone;
    private EditText metAccount;
    //private EditText metPassword;
    private Button mbtnRegister;
    private EditText metVerify;
    private Button mbtnVerify;
    private ProgressDialog mProgressDialog;
    private String localCookie;
    private boolean ready;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);
        initView();
    }

    private void initView() {
        metPhone = (EditText) findViewById(R.id.et_register_phone);
        metAccount = (EditText) findViewById(R.id.et_register_account);
        mbtnRegister = (Button) findViewById(R.id.bt_register);
        mbtnRegister.setOnClickListener(this);

        metVerify = (EditText) findViewById(R.id.et_verity);
        mbtnVerify = (Button) findViewById(R.id.bt_verity);
        mbtnVerify.setOnClickListener(this);

        ((TextView) findViewById(R.id.tv_title)).setText("注册");
        ((ImageView) findViewById(R.id.iv_title_left)).setImageResource(R.drawable.ic_back);
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        Preferences preferences = new Preferences(this);
        Common.isShowSmsVerification = preferences.getPreferenceBooleanValue("isShowSmsVerification");
        if (Common.isShowSmsVerification) {
            findViewById(R.id.isVerification).setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * 提交验证码
     */
    private void resultVerify() {
        mProgressDialog = ProgressDialog.show(this, "提示", "系统正在处理，请稍后…", false, false);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = Common.mUrl + "/PHP/sms_send.php?action=verification&code=" + mVerify + "&phone=" + mPhone;
        Log.i(TAG, url, true);
        JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject object) {
                try {
                    Log.i(TAG, object.toString(), true);
                    if (object.getBoolean("status")) {
                        request_register();
                    } else {
                        mProgressDialog.dismiss();
                        Toast.makeText(RegisterActivity.this, object.getString("info"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    mProgressDialog.dismiss();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressDialog.dismiss();
            }
        }) {
            //重写getHeaders 默认的key为cookie，value则为localCookie
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (localCookie != null && localCookie.length() > 0) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", localCookie);
                    Log.i("调试", "headers----------------" + headers, true);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        requestQueue.add(request);
    }

    /**
     * 注册
     */
    private void request_register() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = "";
        try {
            url = Common.submitFreeRegisterPath() + "regnum=" + mPhone + "&regpwd=" + metAccount.getText().toString().trim() + "&acct=" + URLEncoder.encode(Common.mAgentName, "utf-8") + "&airpwd=net";
        } catch (Exception e) {
        }
        Log.i("RegisterActivity", "request_register_url:" + url, true);

        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                Log.i("RegisterActivity", "request_register:" + s, true);
                if (s != null && s.length() > 0) {
                    String code = ParseXML.parseResponseXML(s, "Ret");
                    if (code.equals("0")) {
                        Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_LONG).show();
                        RegisterActivity.this.finish();
                    } else if (code.equals("2")) {
                        Toast.makeText(RegisterActivity.this, "用户已经注册，请直接的登录", Toast.LENGTH_LONG).show();
                    } else if (code.equals("3")) {
                        Toast.makeText(RegisterActivity.this, "注册失败,代理商错误", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(RegisterActivity.this, "注册失败,未知错误", Toast.LENGTH_LONG).show();
                    }
                    mProgressDialog.dismiss();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.i("RegisterActivity", "错误 = " + volleyError.getLocalizedMessage(), true);
                Toast.makeText(RegisterActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                mProgressDialog.dismiss();
            }
        });

        requestQueue.add(request);


    }


    private void DiaLog() {

        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessage("请选择验证方式");
        builder.setTitle("温馨提示");
        builder.setPositiveButton("短信验证", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                request_verify(true);
                //设置你的操作事项
            }
        });

        builder.setNegativeButton("语音验证",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        request_verify(false);
                    }
                });

        builder.create().show();
    }

    private void request_verify(boolean type) {
        mPhone = metPhone.getText().toString().trim();
        mProgressDialog = ProgressDialog.show(this, "提示", "系统正在处理，请稍后…", false, false);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = "";
        try {
            if (type) {
                url = Common.mUrl + "PHP/sms_send.php?action=send&phone=" + mPhone + "&agent_name=" + URLEncoder.encode(Common.mAgentName, "utf-8");
            } else {
                url = Common.mUrl + "PHP/sms_send.php?action=send_m&phone=" + mPhone + "&agent_name=" + URLEncoder.encode(Common.mAgentName, "utf-8");

            }
        } catch (UnsupportedEncodingException e) {

        }
        Log.i("RegisterActivity", url, true);

        JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject object) {
                Log.i("RegisterActivity    ==== ", object.toString(), true);
                try {
                    if (object.getBoolean("status")) {
                        starTimerTask();
                    }
                    mProgressDialog.dismiss();
                    Toast.makeText(RegisterActivity.this, object.getString("info"), Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener()

        {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.i("RegisterActivity", "错误 = " + volleyError.getLocalizedMessage(), true);
                Toast.makeText(RegisterActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                mProgressDialog.dismiss();
            }
        }) {
            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                Response<JSONObject> superResponse = super
                        .parseNetworkResponse(response);
                Map<String, String> responseHeaders = response.headers;
                String rawCookies = responseHeaders.get("Set-Cookie");
                //Constant是一个自建的类，存储常用的全局变量
                localCookie = rawCookies.substring(0, rawCookies.indexOf(";"));
                Log.i("sessionid", "sessionid----------------" + localCookie, true);
                return superResponse;
            }
        };
        requestQueue.add(request);


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_register:
                mPhone = metPhone.getText().toString().trim();
                mVerify = metVerify.getText().toString().trim();
                if (mPhone.length() < 11) {
                    Toast.makeText(RegisterActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (metAccount.getText().toString().trim().length() < 0) {
                    Toast.makeText(RegisterActivity.this, "密码至少设置6位", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Common.isShowSmsVerification) {
                    resultVerify();
                } else {
                    mProgressDialog = ProgressDialog.show(this, "提示", "系统正在处理，请稍后…", false, false);
                    request_register();
                }
                break;
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.bt_verity:
                if (metPhone.getText().toString().trim().length() < 11) {
                    Toast.makeText(RegisterActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }
//                requestVerify();
                DiaLog();
                break;
            default:
                break;
        }

    }

    public Timer mTimer = new Timer();// 定时器
    private int count = 60;
    /**
     * 消息处理器的应用
     */
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mbtnVerify.setText("剩" + count + "s");
                    break;
                case 2:
                    mTimer.cancel();//
                    mTimer = null;
                    mbtnVerify.setText("获取验证码");
                    mbtnVerify.setBackgroundColor(Color.parseColor("#08B5C8"));
                    mbtnVerify.setEnabled(true);
                case 3:   //获取短信
//                    Toast.makeText(RegisterActivity.this, "获取短信验证码成功", Toast.LENGTH_SHORT).show();
//                    android.util.Log.e(TAG, "获取短信验证码成功");
                    break;
                case 4:    //验证短信
//                    android.util.Log.e(TAG, "验证码验证成功");
//                    request_register();
                    break;
                case -1:
//                    Toast.makeText(RegisterActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public void starTimerTask() {

        count = 60;
        mbtnVerify.setEnabled(false);
        mbtnVerify.setBackgroundColor(Color.parseColor("#e3e3e3"));
        try {
            if (mTimer != null) {
                mTimer.cancel();// 退出之前的mTimer
                mTimer = null;
            }
            mTimer = new Timer();// new一个Timer,否则会报错

        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

        //创建定时线程执行更新任务
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                count--;
                if (count > 0) {

                    mHandler.sendEmptyMessage(1);// 向Handler发送消息
                } else {
                    mHandler.sendEmptyMessage(2);// 向Handler发送消息停止继续执行
                }

            }
        }, 1000, 1000);// 定时任务
    }

    @Override
    public void postExecute(String paramString) {
        Log.i("RegisterActivity    ==== paramString ", paramString, true);
    }
}
